<script lang="ts" setup>
defineOptions({
  name: "VideoScrollY"
});
import VideoBody from "./VideoBody.vue";
import { debounce, getImg } from "@/utils";
import { cloneDeep } from "lodash-es";
import { useCachedVideoStoreHook } from "@/store/modules/cachedVideo";
import "swiper/swiper-bundle.css";
// import { _ADS_DOMAINS, _ads_ids } from "@/config/ads_ids_var";
import { LocalStorage as storage } from "@/assets/js/storage";
import { useWindowSize } from "@vant/use";
// const hostname = location.hostname;
const route = useRoute();
const cachedVideosStore = useCachedVideoStoreHook();
const dataList = ref<any[]>([]);
const { height } = useWindowSize();

watchEffect(() => {
  const list = cloneDeep(cachedVideosStore.cachedVideoList);
  // if (_ADS_DOMAINS.includes(hostname)) {
  //   for (const i = 2; i < list.length; i += 3) {
  //     if (!isEmptyType(omit(list[i], ["index", "isCollect"]))) {
  //       list.splice(i, 0, {});
  //     }
  //   }
  // }
  dataList.value = list.map((item: any, index: any) => ({
    ...item,
    index: index,
    isCollect: false
  }));
});

function unobserveAllItems() {
  [].forEach.call(videoIndexRef.value.children, element => {
    observerVideoItems.unobserve(element);
  });
}
function observeAllItems() {
  [].forEach.call(videoIndexRef.value.children, element => {
    observerVideoItems.observe(element);
  });
}

const scrollToView = () => {
  const targetId = route.query.id as string;
  const tartgetDom = document.getElementById(targetId);
  if (tartgetDom) {
    tartgetDom.scrollIntoView({
      behavior: "instant"
    });
  }
};
onMounted(async () => {
  if (!dataList.value.length) {
    await cachedVideosStore.fetchVideos();
  }
  nextTick(() => {
    scrollToView();
  });
  nextTick(() => {
    unobserveAllItems();
    observeAllItems();
  });
});

onBeforeUnmount(() => {
  unobserveAllItems();
});

let innerStyle = {
  width: "100%",
  height: "100%"
};

const players = reactive<any>([]);
function handleReady(player: any) {
  players.push(player);
}
function handlePlayEnded() {}
const handleCollect = debounce((index: string | number) => {
  dataList.value[index as number].isCollect =
    !dataList.value[index as number].isCollect;
}, 200);
const videoJsOptions = reactive({
  autoplay: true,
  controls: true,
  fluid: true,
  loop: true,
  muted: true,
  sources: [
    // {
    //   src: getVideo("oceans.mp4"),
    //   type: "video/mp4"
    // }
  ],
  poster: getImg("demo02.jpeg"),
  controlBar: {
    currentTimeDisplay: true,
    timeDivider: true,
    durationDisplay: true,
    remainingTimeDisplay: false,
    children: [
      {
        name: "progressControl"
      },
      {
        name: "durationDisplay"
      }
    ]
  },
  userActions: {
    doubleClick: false
  },
  responsive: false,
  webFullScreen: false
});
function setExpandStyle(introduceItem: any, marginLeft: string, float: string) {
  const el = introduceItem.querySelector(".van-text-ellipsis__action");
  el.style.marginLeft = marginLeft;
  el.style.float = float;
}
function setDomStyle(introduceItem: any) {
  nextTick(() => {
    if (introduceItem.clientHeight <= 200) {
      introduceItem.style["height"] = "initial";
      introduceItem.style.justifyContent = "flex-end";
    } else {
      introduceItem.style.justifyContent = "flex-start";
      introduceItem.style["height"] = "200px";
    }
  });
  introduceItem.style["overflow-y"] = "auto";
  introduceItem.style["overflow-x"] = "hidden";
  setExpandStyle(introduceItem, "16px", "initial");
}

function initialDomStyle(introduceItem: any) {
  introduceItem.style["height"] = "initial";
  introduceItem.style["overflow-y"] = "visible";
  introduceItem.style["overflow-x"] = "visible";
  setExpandStyle(introduceItem, "initial", "right");
}
function handleTouchMove(event: { stopPropagation: () => void }) {
  event.stopPropagation();
  console.log("滑动事件被触发，且未冒泡");
}
function handleClickAction(index: string | number, introduceItem: any) {
  const dataIndex = Number(index);
  if (isNaN(dataIndex) || dataIndex < 0 || dataIndex >= dataList.value.length) {
    console.error("Invalid index:", index);
    return;
  }
  const dataItem = dataList.value[dataIndex];
  dataItem.expand = !dataItem.expand;
  if (dataItem.expand) {
    introduceItem.addEventListener("touchmove", handleTouchMove, {
      passive: true
    });
    setDomStyle(introduceItem);
  } else {
    introduceItem.removeEventListener("touchmove", handleTouchMove, {
      passive: true
    });
    initialDomStyle(introduceItem);
  }
}

const videoIndexRef = ref<any>(null);

const observerVideoItems = new IntersectionObserver(
  entries => {
    entries.forEach(async (entry: any) => {
      const target = entry.target;
      if (entry.isIntersecting === true) {
        const index = target.dataset.index * 1;
        if (unref(dataList).length - index < 10) {
          await cachedVideosStore.fetchVideos();
          unobserveAllItems();
          observeAllItems();
        }
      }
    });
  },
  { threshold: 0.75 }
);
function toggleSound(_index: any) {
  videoJsOptions.muted = !videoJsOptions.muted;
  storage.setItem("mute", videoJsOptions.muted ? 1 : 0);
  players.forEach((item: any) => {
    if (videoJsOptions.muted) {
      item.instance?.mute();
    } else {
      item.instance?.unMute();
    }
  });
}

const _data_ad_channel = ref<any>();
function get_ads_channel(callback: (arg0: any) => void) {
  try {
    const local_data_ad_channel =
      LocalStorage.getItem("data-ad-channel") ||
      getSearchOrHashParam("data-ad-channel");
    const _data_ad_channel = ref<any>(local_data_ad_channel ?? "");
    watch(
      () => data_ad_channel.value,
      newVal => {
        _data_ad_channel.value = newVal?.system_channel_name ?? "";
        callback(_data_ad_channel.value);
      }
    );
    if (!isEmptyType(_data_ad_channel.value)) {
      callback(_data_ad_channel.value);
    }
  } catch (error) {
    console.log(error);
  }
}
get_ads_channel(data => {
  _data_ad_channel.value = data;
});
import { isEmptyType } from "@/assets/js/types";
import { LocalStorage } from "@/assets/js/storage";
import { _css } from "@/utils/dom";
import { getSearchOrHashParam } from "@/utils";
import { data_ad_channel } from "./state";
onMounted(() => {
  _css(document.documentElement, "scroll-snap-type", "y mandatory");
  _css(document.documentElement, "scroll-behavior", "smooth");
});
onUnmounted(() => {
  _css(document.documentElement, "scroll-snap-type", "revert");
  _css(document.documentElement, "scroll-behavior", "revert");
});
</script>

<template>
  <div class="video-index" ref="videoIndexRef">
    <div
      v-for="(item, index) in dataList"
      :key="item.id"
      :virtualIndex="index"
      :data-index="index"
      :id="item.youtubeId"
      class="video-item"
      ref="videoItemRef"
      :style="{
        height: `${height}px`,
        boxSizing: 'border-box',
        paddingBottom: '50px',
        background: '#000'
      }"
    >
      <VideoBody
        v-model:innerStyle="innerStyle"
        v-model:index="item.index"
        v-model:videoJsOptions="videoJsOptions"
        v-model:item="dataList[index]"
        @handlePlayEnded="handlePlayEnded"
        @handleClickAction="handleClickAction"
        @handleCollect="handleCollect"
        @ready="handleReady"
        @toggleSound="toggleSound"
      />
    </div>
  </div>
</template>
<style lang="less" scoped>
.video-index {
  .video-item {
    scroll-snap-align: start;
    scroll-snap-stop: always;
  }
}
</style>
